﻿using System.Text;
using System.Data;
using UFC.DBUtility;
using UFC.Common;
using System.Configuration;
using System.Data.OracleClient;
using System.Xml;
using System.Collections.Generic;
using System;

namespace MESInStore
{
  public   class SendInStoreData
    {

      public void RunInStoreSync()
      {
          DataTable mydt = GetInStore();
          DataTable dt2 = GetInStore2();
          mydt.Merge(dt2);
          if (mydt == null || mydt.Rows.Count <= 0)
          {
             // LogHelp.WriteLog("没有可处理的入库记录");              
          }

          Dictionary<string, string> strList;

           ERPService.PS_SAPServicesHttpService sap = new ERPService.PS_SAPServicesHttpService();
          foreach (DataRow dr in mydt.Rows)
          {
              
              LogHelp.WriteLog("处理入库开始" + dr["CONTAINERINSTOREID"].ToString());
              strList = new Dictionary<string, string>();

              strList.Add("STYPE", dr["STYPE"].ToString());//入库类型
              strList.Add("AUFNR", dr["AUFNR"].ToString());//生产订单号
              strList.Add("MATNR", dr["MATNR"].ToString());//零件号
              strList.Add("MAKTX", dr["MAKTX"].ToString());//零件名称
              strList.Add("ZJX", dr["ZJX"].ToString());//机型
              strList.Add("TJMNG", dr["TJMNG"].ToString());//提交数量
              strList.Add("ZHGSL", dr["ZHGSL"].ToString());//合格数量
              strList.Add("BFSL", dr["BFSL"].ToString()); //报废数量
              strList.Add("ZYCHGSL", dr["ZYCHGSL"].ToString());//一次交检合格数
              //strList.Add("CHARG", dr["CHARG"].ToString());//批次
              if ((dr["CHARG"].ToString()).Split('/').Length > 1)
              {
                  strList.Add("CHARG", (dr["CHARG"].ToString()).Split('/')[1].ToString());//批次 'update:Wangjh 改为纯批次号
              }
              else {
                  strList.Add("CHARG", dr["CHARG"].ToString());//批次
              }
             
              strList.Add("ZZBDSL", dr["ZZBDSL"].ToString());//质保单数量
              strList.Add("ZDLDH", dr["ZDLDH"].ToString());//代料单号
              strList.Add("ZBHGDH", dr["ZBHGDH"].ToString());//不合格品审理单号
              strList.Add("ZWTDW", dr["ZWTDW"].ToString());//委托单位
              strList.Add("FEVOR", dr["FEVOR"].ToString());//生产分厂
              strList.Add("ZBZ", dr["ZBZ"].ToString());//备注
              strList.Add("ZLX", dr["ZLX"].ToString());//类型
              strList.Add("ZGCSC", dr["ZGCSC"].ToString());//工厂试车次数
              strList.Add("ZFJSC", dr["ZFJSC"].ToString());//附加试车次数
              strList.Add("ZJYSC", dr["ZJYSC"].ToString());//检验试车次数
              strList.Add("ZTJSC", dr["ZTJSC"].ToString());//提交试车次数
              strList.Add("ZCNSJ", dr["ZCNSJ"].ToString());//厂内工作时间
              strList.Add("ZGCSJ", dr["ZGCSJ"].ToString());//工厂试车时间
              strList.Add("ZFJSJ", dr["ZFJSJ"].ToString());//附加试车时间
              strList.Add("ZJYSJ", dr["ZJYSJ"].ToString());//检验试车时间
              strList.Add("ZCT", dr["ZCT"].ToString());//车台
              strList.Add("ZWTMS", dr["ZWTMS"].ToString());//问题描述

              strList.Add("LGORT", dr["LGORT"].ToString());//库存地点
              strList.Add("ZLPNUM", dr["ZLPNUM"].ToString());//炉批顺序号
              strList.Add("ZPCTC", dr["ZPCTC"].ToString());//批次投产数量
              strList.Add("ZBC", dr["zbc"].ToString());//设计图版次
              string strXML = CreateXMLForInStore(strList);
              LogHelp.WriteLog("推送的xml"+strXML);
              ERPService.ErpAndAppSyncData mm = new ERPService.ErpAndAppSyncData();
              mm.ReqMsg = strXML;
              ERPService.ErpAndAppSyncDataResponse result = sap.ErpAndAppSyncData(mm);
              LogHelp.WriteLog(result.RespMsg);//返回消息
              if (result != null)
              {
              string strMsg = "";
               strMsg = result.RespMsg;

               UpdateInStoreIntegration(dr["CONTAINERINSTOREID"].ToString());
              if (GetERPRcvXML(strMsg)) 
              {

                  OracleDAL.InsertSyncRecord(dr["CONTAINERINSTOREID"].ToString(), m_cRecordType, "成功", 0);
              }
              else
                  OracleDAL.InsertSyncRecord(dr["CONTAINERINSTOREID"].ToString(), m_cRecordType, strMsg, 1);
              }
              else
              {

              }
          }
      }

        /// <summary>
        /// 入库数据获取
        /// 不带子序号
        /// </summary>
        /// <returns></returns>
        private DataTable GetInStore()
        {
            try
            {
                string strTmp = @"SELECT cci.containerid,w.part_revid zbc,t.aufnr,t.bfsl,t.charg,t.createdate,t.employeeid,t.fevor,
 t.isintegration,t.isuse,t.maktx,t.matnr,t.stype,t.tjmng,t.zbhgdh,t.zbz,t.zlx,t.ZGCSC,t.ZFJSC,t.ZTJSC,t.zcnsj,t.zct,t.zdldh,t.zfjsj,t.zgcsj,t.zjysj,t.zhgsl,t.zjx
 ,t.zjysc,t.zwtdw,t.zwtms,t.zychgsl,t.zzbdsl,t.istransfer,t.containerinstoreid,t.lgort,t.zlpnum,t.zpctc,t.workflowid  FROM CONTAINERINSTORE T
left join workflow w on w.workflowid=t.workflowid  
left join containercurrentinfo cci on cci.containername=t.charg                       
WHERE T.ISUSE = 0
 AND T.ISINTEGRATION = 1
  and cci.containertype!=3";

                DataSet myDS = OracleHelper.Query(strTmp);
                if (myDS == null)
                {
                    return null;
                }
                if (myDS.Tables.Count == 0)
                {
                    return null;
                }
                return myDS.Tables[0];
            }
            catch (Exception e)
            {
                LogHelp.WriteError("生产准备获取", e);
                return null;
            }
        }

        /// <summary>
        /// 带子序号,入库数据获取
        /// </summary>
        /// <returns></returns>
        private DataTable GetInStore2() {
            try
            {
                string strTmp = @" select c2.containerid ,w.part_revid zbc,t.aufnr,0 bfsl,c2.containername charg,t.createdate,t.employeeid,t.fevor,
 t.isintegration,t.isuse,t.maktx,t.matnr,t.stype,t.tjmng,t.zbhgdh,t.zbz,t.zlx,t.ZGCSC,t.ZFJSC,t.ZTJSC,t.zcnsj,t.zct,t.zdldh,t.zfjsj,t.zgcsj,t.zjysj,1 zhgsl,t.zjx
 ,t.zjysc,t.zwtdw,t.zwtms,1 zychgsl,t.zzbdsl,t.istransfer,t.containerinstoreid,t.lgort,t.zlpnum,t.zpctc,t.workflowid 
 from container c 
 left join container c2 on c2.parentcontainerid=c.containerid
 left join CONTAINERINSTORE T on t.charg=c.containername
left join workflow w on w.workflowid=t.workflowid 
 where T.ISUSE = 0 and T.ISINTEGRATION = 1  and c.containertype=3 and c2.status=1                                 
 union all
 --报废的子序号
select c2.containerid ,w.part_revid zbc,t.aufnr,abs(ch.qty) bfsl,c2.containername charg,t.createdate,t.employeeid,t.fevor,
 t.isintegration,t.isuse,t.maktx,t.matnr,t.stype,t.tjmng,t.zbhgdh,t.zbz,t.zlx,t.ZGCSC,t.ZFJSC,t.ZTJSC,t.zcnsj,t.zct,t.zdldh,t.zfjsj,t.zgcsj,t.zjysj,0 zhgsl,t.zjx
 ,t.zjysc,t.zwtdw,t.zwtms,0 zychgsl,t.zzbdsl,t.istransfer,t.containerinstoreid,t.lgort,t.zlpnum,t.zpctc,t.workflowid 
 from checkqtychangerecord ch
 left join containerfinishedcheckinfo cfci on cfci.containerfinishedcheckinfoid=ch.containercheckinfoid and cfci.isuse=0
 left join container c2 on c2.containerid=ch.containerid and c2.parentcontainerid=cfci.containerid
 left join container c on c.containerid=cfci.containerid
 left join CONTAINERINSTORE T on t.charg=c.containername
left join workflow w on w.workflowid=t.workflowid 
 where T.ISUSE = 0 and T.ISINTEGRATION = 1 and c.containertype=3
 and ch.isuse=0 and ch.ChangeQtyType=2 and ch.scrapsourcetype=2   ";

                DataSet myDS = OracleHelper.Query(strTmp);
                if (myDS == null)
                {
                    return null;
                }
                if (myDS.Tables.Count == 0)
                {
                    return null;
                }
                return myDS.Tables[0];
            }
            catch (Exception e)
            {
                LogHelp.WriteError("生产准备获取", e);
                return null;
            }
        }

        private void UpdateInStoreIntegration(string inStoreID)
        {
            string strSql = @"UPDATE CONTAINERINSTORE SET ISINTEGRATION = 0
                            WHERE CONTAINERINSTOREID = :v_recordid";

            OracleParameter[] insertParam = new OracleParameter[1];

            insertParam[0] = new OracleParameter();
            insertParam[0].ParameterName = ":v_recordid";
            insertParam[0].OracleType = OracleType.VarChar;
            insertParam[0].Direction = ParameterDirection.Input;
            insertParam[0].Value = inStoreID;

            int i = OracleHelper.ExecuteSql(strSql, insertParam);
        }

        private string CreateXMLForInStore(Dictionary<string, string> strList)
        {

            XmlDocument doc = new XmlDocument();
            doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", ""));
            XmlNode ReqNode = doc.CreateElement("ReqMsg");
            XmlNode headerNode = doc.CreateElement("header");
            XmlNode senderNode = doc.CreateElement("sendSysName");
            senderNode.InnerText = "APP_MES";
            XmlNode rcvNode = doc.CreateElement("rcvSysName");
            rcvNode.InnerText = "APP_ERP";
            XmlNode extNode = doc.CreateElement("extConfig");
            extNode.AppendChild(doc.CreateElement("isReTry"));
            extNode.LastChild.InnerText = "false";
            extNode.AppendChild(doc.CreateElement("FunName"));
            //extNode.LastChild.InnerText = "ZPPF_MES_06";
            extNode.LastChild.InnerText = "ZPPF_MES_RKXX";
            headerNode.AppendChild(senderNode);
            headerNode.AppendChild(rcvNode);
            headerNode.AppendChild(extNode);
            ReqNode.AppendChild(headerNode);
            XmlNode documentNode = doc.CreateElement("document");
            string strData = "<ALCNRINFO>";// "<ALCNRINFO>";add by yuxj 20170622
            foreach (KeyValuePair<string, string> _key in strList)
            {
                strData = string.Format("{0}<{1}>{2}</{1}>", strData, _key.Key, _key.Value);
            }
            strData += "</ALCNRINFO>"; //add by yuxj 20170622
            documentNode.AppendChild(doc.CreateCDataSection(strData));            
            ReqNode.AppendChild(documentNode);
            doc.AppendChild(ReqNode);
            return doc.InnerXml;
        }

        /// <summary>
        /// 获取ERP反馈XML
        /// </summary>
        /// <param name="strXML"></param>
        /// <returns></returns>
        private bool GetERPRcvXML(string strXML)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(strXML);
            string isSuccess = doc.SelectSingleNode("RespMsg/header/isSuccess").InnerText;
            string meaasge = doc.SelectSingleNode("RespMsg/header/message").InnerText;

            if (isSuccess == "true" || meaasge == "S")
                return true;
            else
            {
                LogHelp.WriteLog(meaasge);
                return false;
            }
        }
        private const string m_cRecordType = "instore";
    }
}
